package com.henghai.zhenxuan.ui.page.adopt;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.henghai.zhenxuan.data.api.PurchaseProductApi;
import com.henghai.zhenxuan.data.bean.AdoptListBean;
import com.henghai.zhenxuan.data.bean.AdoptionOrderBean;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.AdoptListRequester;
import com.henghai.zhenxuan.pay.wechat.pay.WechatPay;
import com.henghai.zhenxuan.ui.page.adapter.AdoptAdapter;
import com.henghai.zhenxuan.utils.HiRes;
import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.R;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnBackgroundMaskClickListener;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.interfaces.OnIconChangeCallBack;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.interfaces.OnSuccessAndErrorListener;
import com.tamsiree.rxkit.view.RxToast;
import com.tamsiree.rxpay.alipay.AliPayModel;
import com.tamsiree.rxpay.alipay.AliPayTool;
import com.tamsiree.rxpay.wechat.pay.WechatPayTools;

import java.util.ArrayList;
import java.util.List;

/**
 * 领养中心
 */
public class AdoptFragment extends BaseFragment {
    private AdoptStates mStates;
    private RefreshLayout mRefreshLayout;
    private AdoptAdapter adapter;
    private AdoptListRequester adoptListRequester;
    private PageMessenger mMessenger;
    private int payType = 0; //0 支付宝 1 微信


    private static final String TAG = "AdoptFragment";

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(AdoptStates.class);
        adoptListRequester = getFragmentScopeViewModel(AdoptListRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adoptListRequester.getAdoptListTaskResult().observe(this, httpBeanDataResult -> {
            if (mRefreshLayout != null) {
                mRefreshLayout.finishRefresh();
                mRefreshLayout.finishLoadMore();
            }
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            if (httpBeanDataResult.getResult().getData() == null) {
                return;
            }
            mStates.rows = httpBeanDataResult.getResult().getData().getRows().size();
            List<AdoptListBean.RowsDTO> list = new ArrayList<>();
            list.addAll(mStates.taskList.get());
            list.addAll(httpBeanDataResult.getResult().getData().getRows());
            mStates.taskList.set(list);
        });
//        adoptListRequester.getAdoptResult().observe(getViewLifecycleOwner(), httpBeanDataResult -> {
//            if (httpBeanDataResult.getResponseStatus().isSuccess()) {
//                TipDialog.show("领养成功", WaitDialog.TYPE.SUCCESS);
//                mMessenger.input(new Messages(Messages.EVENT_ADOPT_PET));
//            }
//            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
//                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), TipDialog.TYPE.ERROR);
//                return;
//            }
//        });
        adoptListRequester.requestAdoptList(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);

        adoptListRequester.getAdoptionOrderResult().observe(getViewLifecycleOwner(), httpBeanDataResult -> {
            if (httpBeanDataResult.getResponseStatus().isSuccess()) {
                AdoptionOrderBean adoptionOrderBean = httpBeanDataResult.getResult().getData();
                String orderNo = adoptionOrderBean.getOrderNo();//订单号
                String money = adoptionOrderBean.getTotalAmount().toString();//订单金额
                String orderName = adoptionOrderBean.getOrderDesc();//订单标题
                String detail = adoptionOrderBean.getRemark();//订单详情
                Log.d(TAG, "onViewCreated: " + adoptionOrderBean);
                //弹出支付方式选择框
                ArrayList<CharSequence> list = new ArrayList<>();
                list.add("支付宝");
                list.add("微信");
                BottomMenu.show(list)
                        .setOnIconChangeCallBack(new OnIconChangeCallBack<BottomMenu>() {
                            @Override
                            public int getIcon(BottomMenu dialog, int index, String menuText) {
                                switch (menuText) {
                                    case "支付宝":
                                        return R.mipmap.icon_cash_ali;
                                    case "微信":
                                        return R.mipmap.icon_cash_wx;
                                }
                                return 0;
                            }
                        })
                        .setTitle("选择支付方式")
                        .setOnMenuItemClickListener((dialog, text, index) -> {
                            switch (index) {
                                case 0:
                                    payType = 0;
                                    //支付宝支付
                                    AliPayTool.aliPay(getActivity(), Const.ALIPAY_APP_ID, true,
                                            Const.ALIPAY_RSA_PRIVATE, new AliPayModel(orderNo, money, orderName, detail), new OnSuccessAndErrorListener() {
                                                @Override
                                                public void onSuccess(@Nullable String s) {
                                                    Log.d(TAG, "onSuccess: " + s);
                                                    RxToast.showToast(s);
                                                    mMessenger.input(new Messages(Messages.EVENT_ADOPT_PET));
                                                }

                                                @Override
                                                public void onError(@Nullable String s) {
                                                    Log.d(TAG, "onError: " + s);
                                                    RxToast.showToast(s);
                                                }

                                            });
                                    break;
                                case 1:
                                    payType = 1;
                                    //微信支付
                                    WechatPay.getInstance().doPay("orderInfo", new WechatPay.WechatPayResultCallBack() {
                                        @Override
                                        public void onSuccess() {
                                            RxToast.showToast("支付成功");
                                        }

                                        @Override
                                        public void onError(int errorCode) {
                                            RxToast.showToast("支付失败");
                                        }

                                        @Override
                                        public void onCancel() {
                                            RxToast.showToast("支付取消");
                                        }

                                    });
                                    break;
                            }
                            return false;
                        });


            }
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), TipDialog.TYPE.ERROR);
            }
        });

        mMessenger.output(this, messages -> {
        });
    }


    @Override
    protected DataBindingConfig getDataBindingConfig() {
        adapter = new AdoptAdapter(getContext());
        adapter.setOnItemBtClickListener(new AdoptAdapter.OnItemBtClickListener() {
            @Override
            public void onItemDelClick(AdoptListBean.RowsDTO adoptBean, int postion) {
                //领养
                CustomDialog.build()
                        .setMaskColor(HiRes.INSTANCE.getColor(R.color.grey_50_40))
                        .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_adoptillustrate) {
                            @Override
                            public void onBind(CustomDialog dialog, View v) {
                                ImageView imageView = v.findViewById(R.id.adoptdialog_colse_img);
                                TextView adoptIllustrateTv = v.findViewById(R.id.adopt_illustrate_tv);
                                TextView welfareIllustrateTv = v.findViewById(R.id.welfare_illustrate_tv);
                                TextView classIllustrate = v.findViewById(R.id.class_illustrate);
                                TextView priceTv = v.findViewById(R.id.price_tv);
                                TextView adoptPlayTv = v.findViewById(R.id.adopt_play_tv);
                                adoptIllustrateTv.setText(TextUtils.isEmpty(adoptBean.getPetAdoptInstructions()) ? "" : adoptBean.getPetAdoptInstructions());
                                welfareIllustrateTv.setText(TextUtils.isEmpty(adoptBean.getPetWelfareInstructions()) ? "" : adoptBean.getPetWelfareInstructions());
                                classIllustrate.setText("鹅苗价格:");
                                priceTv.setText(adoptBean.getPetPrice() == null ? "0" : String.valueOf(adoptBean.getPetPrice()));
                                adoptPlayTv.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Log.d(TAG, "onClick: " + priceTv.getText().toString());
                                        adoptListRequester.adoptionOrderResult(getViewLifecycleOwner(), adoptBean.getPetId(), 1);
                                        dialog.dismiss();
                                    }
                                });
                                imageView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                            }
                        })
                        .setOnBackgroundMaskClickListener(new OnBackgroundMaskClickListener<CustomDialog>() {
                            @Override
                            public boolean onClick(CustomDialog dialog, View v) {
                                return true;
                            }
                        })
                        .show();
            }
        });
        return new DataBindingConfig(R.layout.fragment_adopt, BR.vm, mStates)
                .addBindingParam(BR.adapter, adapter)
                .addBindingParam(BR.listener, new ListenerRefreshHandler())
                .addBindingParam(BR.loadListener, new ListenerLoadHandler());
    }


    public class ListenerRefreshHandler implements OnRefreshListener {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            mStates.pageNum = 1;
            mRefreshLayout = refreshLayout;
            mStates.taskList.set(new ArrayList<>());
            adoptListRequester.requestAdoptList(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);
        }
    }

    public class ListenerLoadHandler implements OnLoadMoreListener {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            mRefreshLayout = refreshLayout;
            if (mStates.rows >= Integer.parseInt(mStates.PageSize)) {
                mStates.pageNum++;
                adoptListRequester.requestAdoptList(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);
            } else {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    }

    public static class AdoptStates extends StateHolder {
        public int pageNum = 1;
        public int rows;
        public final String PageSize = "20";
        public final State<List<AdoptListBean.RowsDTO>> taskList = new State<>(new ArrayList<>());
    }


}
